<template>
  <div class="container max-w-6xl p-4 bg-white bg-opacity-60 my-4 rounded-lg backdrop-blur-md">
    <div class="flex flex-col items-center space-y-4 my-4">
      <InputText v-model="name" placeholder="专辑名称" />
      <InputText v-model="description" placeholder="专辑简介" />
      <div>
        <input ref="file" accept="image/*" type="file" class="hidden" @change="changeImg" />
        <Button label="更改封面" icon="far fa-pen" @click="file.click()" class="p-button-sm" />
      </div>
      <img
        ref="img"
        src="https://pic.brooke-zb.top/fashion_textile/default_album_picture.png"
        alt="专辑封面"
        width="240"
      />
      <Button label="创建专辑" @click="_createAlbum" />
    </div>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  name: 'DesignerCreateAlbum'
})
</script>

<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { useToast } from 'primevue/usetoast'
import { useRouter } from 'vue-router'
import { createAlbum } from '@/api/designer/designer'

import InputText from 'primevue/inputtext'
import Button from 'primevue/button'

let toast = useToast()
const router = useRouter()

const name = ref('')
const description = ref('')
const file = ref()
const img = ref()
const uploadImg = ref<File>()

function changeImg() {
  if (file.value.files.length > 0) {
    let reads = new FileReader()
    let f = file.value.files[0]
    uploadImg.value = f
    reads.readAsDataURL(f)
    reads.onload = () => {
      img.value.src = reads.result
    }
  }
}

async function _createAlbum() {
  if (name.value.length === 0) {
    toast.add({
      severity: 'error',
      summary: '创建失败',
      detail: '请输入专辑名称',
      life: 3000
    })
    return
  }

  let album = new FormData()
  album.append('worksAlbum', JSON.stringify({
    name: name.value,
    description: description.value ? description.value : '这个人很懒，什么都没有留下',
  }))
  if (uploadImg.value) {
    album.append('picture', uploadImg.value)
  }

  // 上传专辑
  createAlbum(album)
    .then(() => {
      toast.add({
        severity: 'success',
        summary: '创建成功',
        detail: '专辑创建成功',
        life: 3000
      })
      setTimeout(() => {
        router.push('/designer/center')
      }, 1000)
    })
    .catch(err => {
      toast.add({
        severity: 'error',
        summary: '创建失败',
        detail: err.data.msg,
        life: 3000
      })
    })
}
</script>